package com.http.client;


import android.app.Service;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.http.FileThread;
import com.http.HttpFactory;
import com.http.HttpUtil;
import com.http.callback.RequestCallBack;
import com.http.method.FileRequest;
import com.thread.ThreadExecutor;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mac_wk on 14-12-10.
 */
public class DownFileManager implements Runnable{
    public static final int DOWNFILE = 1;
    public static final int DOWNFILE_COMMPLETE=2;
    private static final int START = 3;
    private FileRequest fileRequest;
    private int file_length;
    private int nowCount;
    //默认是3个线程下载
    private int splite = 3;
    private List<FileThread> fileThreads = new ArrayList<FileThread>();
    private RequestCallBack requestCallBack;
    //开始时间
    private long startTime;
    //时间间隔
    private long time_spec=1000;
    private long time_tmp;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case DOWNFILE:
                    process(msg.arg1);
                    break;
                case START:
                    requestCallBack.start(msg.arg1);
                    break;
            }
        }
    };
    private void process(int count) {
        nowCount+=count;
        long nowTime = System.currentTimeMillis();
        long userTime = (nowTime-startTime);
        if(userTime-time_tmp>=time_spec)
        {
            if (userTime==0)userTime=1;
            time_tmp = userTime;
            userTime = userTime/1000;
            long speed = nowCount/userTime;
            //总共用得时间
            long total_time = file_length/speed*1000;
            //还剩多少时间
            long leave_time = total_time-time_tmp;
            requestCallBack.process(file_length,nowCount,speed,leave_time);
        }
        if (nowCount>=file_length)
        {
            requestCallBack.process(file_length,nowCount,0,0);
            requestCallBack.success("下载成功");
        }

    }


    public void startDownFile(String url,File dir,int method,RequestCallBack requestCallBack)
    {

        if (!dir.exists())
        {
            dir.mkdirs();
        }
        fileRequest = new FileRequest(url,dir);
        fileRequest.setMethod(method);
        this.requestCallBack = requestCallBack;
        ThreadExecutor.executor(this);
    }
    public void startDownFile(String url,File dir,RequestCallBack requestCallBack)
    {
        startDownFile(url, dir, HttpUtil.GET, requestCallBack);
    }
    public void pause()
    {
        for (FileThread fileThread:fileThreads)
        {
            fileThread.getFileRequest().setPause(true);
        }
    }
    public void resume(){

    }
    @Override
    public void run() {
        try {
            startTime = System.currentTimeMillis();
            HttpURLConnection httpURLConnection = HttpFactory.createHttp(fileRequest);
            int length = httpURLConnection.getContentLength();
            Message message = handler.obtainMessage(START,length,0);
            message.sendToTarget();
            this.file_length = length;
            int sp = length/splite;
            int l = length%3;
            int  position = 0;
            File file = new File(fileRequest.getFile(),"tmp.pdf");
            if (file.exists())
                file.delete();
            for (int i = 0;i<splite;i++)
            {
                FileRequest fr = null;
                if ((i+1)==splite)
                {
                    fr = new FileRequest(fileRequest.getmUrl(),file,position,sp+position+l);
                }else
                {
                    fr = new FileRequest(fileRequest.getmUrl(),file,position,sp+position);
                }
                position+=sp;
                HttpURLConnection httpURLConnection_file = HttpFactory.createHttp(fr);
                FileThread fileThread = new FileThread(fr,httpURLConnection_file,handler);
                fileThreads.add(fileThread);
            }
            //开始任务
            for(FileThread fileThread:fileThreads)
            {
                ThreadExecutor.executor(fileThread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int getSplite() {
        return splite;
    }

    public void setSplite(int splite) {
        this.splite = splite;
    }
}
